<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>城市天气类型统计 | WeatherViz Pro</title>
    <!-- 引入Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- 引入Font Awesome -->
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <!-- 引入ECharts -->
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>

    <!-- 全局颜色变量 -->
    <style>
        :root {
            --primary: #00FFFF;       /* 主色 - 霓虹蓝 */
            --secondary: #00FF7F;     /* 辅助色 - 全息绿 */
            --dark-bg: #0F172A;       /* 深色背景 - 增加亮度提高对比度 */
            --light-text: #FFFFFF;    /* 浅色文字 - 改为纯白色 */
            --medium-text: #A8C7FF;   /* 中色文字 - 增加亮度提高对比度 */
            --accent: #FF5722;        /* 强调色 - 橙红 */
            --card-bg: rgba(15, 23, 42, 0.7); /* 卡片背景 */
            --card-border: rgba(0, 255, 255, 0.2); /* 卡片边框 - 增加透明度 */
        }
    </style>

    <!-- 配置Tailwind自定义主题 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: 'var(--primary)',
                        secondary: 'var(--secondary)',
                        accent: 'var(--accent)',
                        dark: 'var(--dark-bg)',
                        light: 'var(--light-text)',
                        medium: 'var(--medium-text)',
                        card: {
                            bg: 'var(--card-bg)',
                            border: 'var(--card-border)'
                        },
                        success: '#52C41A',
                        warning: '#FAAD14',
                        danger: '#FF4D4F',
                        neutral: {
                            100: '#F5F7FA',
                            200: '#E4E7ED',
                            300: '#DCDFE6',
                            400: '#C0C4CC',
                            500: '#909399',
                            600: '#606266',
                            700: '#303133',
                            800: 'var(--dark-bg)',
                        }
                    },
                    fontFamily: {
                        inter: ['Inter', 'system-ui', 'sans-serif'],
                    },
                    boxShadow: {
                        'card': '0 4px 20px rgba(0, 255, 255, 0.1)',
                        'card-hover': '0 8px 30px rgba(0, 255, 255, 0.2)',
                        'neon': '0 0 10px rgba(0, 255, 255, 0.5), 0 0 20px rgba(0, 255, 255, 0.3)',
                    }
                }
            }
        }
    </script>

    <!-- 自定义工具类 -->
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .glass-effect {
                backdrop-filter: blur(8px);
            }
            .card-animate {
                transition: all 0.3s ease;
            }
            .card-animate:hover {
                transform: translateY(-5px);
                box-shadow: 0 8px 30px rgba(0, 255, 255, 0.2);
            }
            .text-neon {
                text-shadow: 0 0 10px rgba(0, 255, 255, 0.5);
            }
            .neon-border {
                border: 1px solid rgba(0, 255, 255, 0.2);
            }

            /* 天气类型渐变（科技感配色） */
            .weather-gradient-sunny {
                background: linear-gradient(135deg, #FFD700 0%, #FFA500 100%);
            }
            .weather-gradient-cloudy {
                background: linear-gradient(135deg, #87CEEB 0%, #4682B4 100%);
            }
            .weather-gradient-overcast {
                background: linear-gradient(135deg, #DCDCDC 0%, #808080 100%);
            }
            .weather-gradient-rainy {
                background: linear-gradient(135deg, #6495ED 0%, #00008B 100%);
            }
            .weather-gradient-snowy {
                background: linear-gradient(135deg, #B0E2FF 0%, #00BFFF 100%);
            }
            .weather-gradient-foggy {
                background: linear-gradient(135deg, #D4D4D4 0%, #AAAAAA 100%);
            }
            .weather-gradient-thunderstorm {
                background: linear-gradient(135deg, #4A4A4A 0%, #222222 100%);
            }
        }
    </style>
</head>
<body class="font-inter bg-neutral-800 text-light min-h-screen">
    <!-- 顶部导航栏 -->
    <header class="bg-card-bg neon-border shadow-sm sticky top-0 z-50 transition-all duration-300 glass-effect" id="mainHeader">
        <div class="container mx-auto px-4 py-4 flex justify-between items-center">
            <div class="flex items-center space-x-2">
                <i class="fa fa-cloud text-primary text-2xl text-neon"></i>
                <h1 class="text-xl font-bold text-light">城市天气类型统计</h1>
            </div>

            <!-- 返回首页功能 -->
            <div class="flex items-center space-x-4">
                <div class="text-sm text-medium">
                    <span id="currentDate">加载中...</span>
                </div>

            </div>
        </div>
    </header>

    <main class="container mx-auto px-4 py-8 max-w-6xl">
        <!-- 城市选择器 -->
        <div class="bg-card-bg neon-border rounded-xl shadow-card p-6 mb-8 transform transition-all duration-300 hover:shadow-card-hover">
            <form id="weatherForm">
                <div class="flex flex-col md:flex-row gap-4">
                    <div class="flex-1">
                        <label for="urban" class="block text-sm font-medium text-medium mb-2">选择城市</label>
                        <div class="relative">
                            <select name="urban" id="urban" class="w-full bg-neutral-700 border border-card-border rounded-lg py-3 px-4 pr-8 appearance-none focus:outline-none focus:ring-2 focus:ring-primary/50 transition-all text-light">
                                <option value="">请选择城市</option>
                                {% for city in cities %}
                                <option value="{{ city }}"
                                        {% if city == urban %}selected{% endif %}
                                        data-weather-count="{{ cities_weather_counts[city] }}">
                                    {{ city }}（{{ cities_weather_counts[city] }}天数据）
                                </option>
                                {% endfor %}
                            </select>
                            <div class="pointer-events-none absolute inset-y-0 right-0 flex items-center px-2 text-medium">
                                <i class="fa fa-chevron-down text-xs"></i>
                            </div>
                        </div>
                    </div>
                    <button type="button" id="searchButton" class="bg-primary hover:bg-secondary text-neutral-800 font-medium py-3 px-6 rounded-lg transition-all duration-300 transform hover:scale-105 flex items-center justify-center gap-2 shadow-neon">
                        <i class="fa fa-search"></i>
                        <span>查询天气统计</span>
                    </button>
                </div>
            </form>
        </div>

        <!-- 错误提示 -->
        <div id="chartError" class="fixed top-4 right-4 bg-danger text-white py-3 px-6 rounded-lg shadow-lg transform transition-all duration-300 translate-y-[-100px] opacity-0 flex items-center gap-2 z-50">
            <i class="fa fa-exclamation-circle"></i>
            <span id="errorMessage">错误提示</span>
        </div>

        <!-- 数据概览卡片 -->
        <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
            <div class="bg-card-bg neon-border rounded-xl shadow-card p-6 transform transition-all duration-300 hover:shadow-card-hover hover:scale-[1.02]">
                <div class="flex justify-between items-start mb-4">
                    <div>
                        <p class="text-sm text-medium">当前城市</p>
                        <h3 class="text-2xl font-bold text-light mt-1" id="currentCity">加载中...</h3>
                    </div>
                    <div class="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center">
                        <i class="fa fa-map-marker text-primary"></i>
                    </div>
                </div>
                <div class="text-sm text-medium">
                    <span class="flex items-center"><i class="fa fa-calendar-o mr-2"></i><span id="dateRange">数据覆盖期: 加载中...</span></span>
                </div>
            </div>

            <div class="bg-card-bg neon-border rounded-xl shadow-card p-6 transform transition-all duration-300 hover:shadow-card-hover hover:scale-[1.02]">
                <div class="flex justify-between items-start mb-4">
                    <div>
                        <p class="text-sm text-medium">统计天数</p>
                        <h3 class="text-2xl font-bold text-light mt-1" id="totalDays">加载中...</h3>
                    </div>
                    <div class="w-10 h-10 rounded-full bg-secondary/10 flex items-center justify-center">
                        <i class="fa fa-calendar-check-o text-secondary"></i>
                    </div>
                </div>
                <div class="text-sm text-medium">
                    <span class="flex items-center"><i class="fa fa-refresh mr-2"></i><span id="updateTime">数据更新时间: 加载中...</span></span>
                </div>
            </div>

            <div class="bg-card-bg neon-border rounded-xl shadow-card p-6 transform transition-all duration-300 hover:shadow-card-hover hover:scale-[1.02]">
                <div class="flex justify-between items-start mb-4">
                    <div>
                        <p class="text-sm text-medium">天气类型</p>
                        <h3 class="text-2xl font-bold text-light mt-1" id="weatherTypesCount">加载中...</h3>
                    </div>
                    <div class="w-10 h-10 rounded-full bg-success/10 flex items-center justify-center">
                        <i class="fa fa-cloud text-success"></i>
                    </div>
                </div>
                <div class="text-sm text-medium">
                    <span class="flex items-center"><i class="fa fa-bar-chart mr-2"></i>包含晴、多云、雨等类型</span>
                </div>
            </div>
        </div>

        <!-- 图表容器 -->
        <div class="bg-card-bg neon-border rounded-xl shadow-card p-6 mb-8 transform transition-all duration-300 hover:shadow-card-hover">
            <div class="flex justify-between items-center mb-6">
                <h2 class="text-xl font-bold text-light">天气类型分布</h2>
                <div class="flex space-x-2">
                    <button id="chartZoomIn" class="p-2 rounded-lg bg-neutral-700 hover:bg-primary/20 transition-colors text-light">
                        <i class="fa fa-search-plus"></i>
                    </button>
                    <button id="chartZoomOut" class="p-2 rounded-lg bg-neutral-700 hover:bg-primary/20 transition-colors text-light">
                        <i class="fa fa-search-minus"></i>
                    </button>
                    <button id="chartRefresh" class="p-2 rounded-lg bg-neutral-700 hover:bg-primary/20 transition-colors text-light">
                        <i class="fa fa-refresh"></i>
                    </button>
                </div>
            </div>

            <div class="relative">
                <div id="chartLoading" class="absolute inset-0 bg-neutral-800/80 flex items-center justify-center z-10">
                    <div class="text-center">
                        <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-primary mb-2"></div>
                        <p class="text-medium">数据加载中...</p>
                    </div>
                </div>
                <div id="weatherChart" style="width: 100%; height: 450px;"></div>
            </div>
        </div>

        <!-- 天气卡片容器 -->
        <div class="bg-card-bg neon-border rounded-xl shadow-card p-6 transform transition-all duration-300 hover:shadow-card-hover">
            <div class="flex justify-between items-center mb-6">
                <h2 class="text-xl font-bold text-light">天气类型详情</h2>
                <div class="text-sm text-medium">
                    <span id="weatherCardCount">加载中...</span>
                </div>
            </div>

            <div id="weatherCards" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
                <!-- 动态生成的天气卡片将在这里显示 -->
            </div>
        </div>
    </main>

    <footer class="bg-card-bg neon-border border-t border-card-border mt-12">
        <div class="container mx-auto px-4 py-8">
            <div class="flex flex-col md:flex-row justify-between items-center">
                <div class="mb-4 md:mb-0">
                    <p class="text-sm text-medium">© 2025 城市天气统计系统 | 数据仅供参考</p>
                </div>
                <div class="flex space-x-4">
                    <a href="#" class="text-medium hover:text-primary transition-colors">
                        <i class="fa fa-question-circle"></i> 帮助中心
                    </a>
                    <a href="#" class="text-medium hover:text-primary transition-colors">
                        <i class="fa fa-info-circle"></i> 关于我们
                    </a>
                    <a href="#" class="text-medium hover:text-primary transition-colors">
                        <i class="fa fa-envelope-o"></i> 联系我们
                    </a>
                </div>
            </div>
        </div>
    </footer>

    <script>
        // 天气图标配置（保持原有配色方案，增加更多天气类型）
        const WEATHER_CONFIG = {
            '晴': { icon: 'fa-sun-o', color: '#FFD700', gradient: 'weather-gradient-sunny', class: 'bg-yellow-100/20 border-yellow-200/30' },
            '多云': { icon: 'fa-cloud', color: '#87CEEB', gradient: 'weather-gradient-cloudy', class: 'bg-blue-100/20 border-blue-200/30' },
            '阴': { icon: 'fa-cloud', color: '#696969', gradient: 'weather-gradient-overcast', class: 'bg-gray-100/20 border-gray-200/30' },
            '雨': { icon: 'fa-tint', color: '#6495ED', gradient: 'weather-gradient-rainy', class: 'bg-blue-200/20 border-blue-300/30' },
            '雪': { icon: 'fa-snowflake-o', color: '#B0E2FF', gradient: 'weather-gradient-snowy', class: 'bg-blue-50/20 border-blue-100/30' },
            '雾': { icon: 'fa-fog', color: '#D4D4D4', gradient: 'weather-gradient-foggy', class: 'bg-gray-100/20 border-gray-200/30' },
            '雷阵雨': { icon: 'fa-bolt', color: '#4A4A4A', gradient: 'weather-gradient-thunderstorm', class: 'bg-gray-200/20 border-gray-300/30' },
            '_default': { icon: 'fa-question-circle', color: '#666', gradient: 'bg-gradient-to-br from-neutral-100/20 to-neutral-200/20', class: 'bg-neutral-100/20 border-neutral-200/30' }
        };

        // 初始化页面数据
        let weatherData = {
            urban: '{{ urban }}',
            types: {{ weather_types|tojson }},
            counts: {{ counts|tojson }},
            total_days: {{ total_days }},
            start_date: '{{ start_date }}',
            end_date: '{{ end_date }}',
            update_time: '{{ update_time }}'
        };

        // 初始化图表
        let weatherChart;
        function initChart() {
            const chartDom = document.getElementById('weatherChart');
            weatherChart = echarts.init(chartDom, null, {renderer: 'canvas'});

            const option = {
                backgroundColor: 'transparent',
                tooltip: {
                    trigger: 'item',
                    backgroundColor: 'rgba(15, 23, 42, 0.9)',
                    borderColor: 'rgba(0, 255, 255, 0.3)',
                    borderWidth: 1,
                    padding: 12,
                    textStyle: {
                        color: '#FFFFFF',
                        fontFamily: 'Inter, sans-serif'
                    },
                    formatter: ({ name, value, percent }) => `
                        <div class="text-sm">
                            <div class="flex items-center mb-1">
                                <i class="fa ${WEATHER_CONFIG[name]?.icon || 'fa-question-circle'} text-lg mr-2" style="color:${WEATHER_CONFIG[name]?.color || '#666'}"></i>
                                <span class="font-medium">${name}</span>
                            </div>
                            <div class="flex justify-between mt-1">
                                <span>天数:</span>
                                <span class="font-medium">${value} 天</span>
                            </div>
                            <div class="flex justify-between mt-1">
                                <span>占比:</span>
                                <span class="font-medium">${percent}%</span>
                            </div>
                        </div>
                    `
                },
                legend: {
                    type: 'scroll',
                    orient: 'horizontal',
                    bottom: 10,
                    itemWidth: 12,
                    itemHeight: 12,
                    pageIconColor: '#00FFFF',
                    textStyle: {
                        color: '#A8C7FF',
                        fontFamily: 'Inter, sans-serif',
                        fontSize: 12
                    }
                },
                series: [{
                    type: 'pie',
                    radius: ['40%', '70%'],
                    center: ['50%', '45%'],
                    data: weatherData.types.map((type, index) => ({
                        name: type,
                        value: weatherData.counts[index],
                        itemStyle: {
                            borderRadius: 4,
                            shadowBlur: 10,
                            shadowColor: 'rgba(0, 255, 255, 0.1)'
                        }
                    })),
                    label: {
                        formatter: '{b|{b}}\n{d|{d}%}',
                        rich: {
                            b: {
                                fontSize: 12,
                                lineHeight: 20,
                                color: '#FFFFFF'
                            },
                            d: {
                                fontSize: 12,
                                lineHeight: 20,
                                color: '#A8C7FF'
                            }
                        }
                    },
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 20,
                            shadowColor: 'rgba(0, 255, 255, 0.3)'
                        }
                    }
                }]
            };

            // 设置图表颜色
            option.series[0].itemStyle = {
                color: (params) => {
                    const config = WEATHER_CONFIG[params.name] || WEATHER_CONFIG._default;
                    return config.color;
                }
            };

            weatherChart.setOption(option);

            // 响应式调整
            window.addEventListener('resize', () => weatherChart.resize());

            // 图表交互按钮
            document.getElementById('chartZoomIn').addEventListener('click', () => {
                weatherChart.dispatchAction({
                    type: 'dataZoom',
                    zoom: 1.1
                });
            });

            document.getElementById('chartZoomOut').addEventListener('click', () => {
                weatherChart.dispatchAction({
                    type: 'dataZoom',
                    zoom: 0.9
                });
            });

            document.getElementById('chartRefresh').addEventListener('click', () => {
                fetchWeatherData(weatherData.urban);
            });
        }

        // 渲染天气卡片
        function renderWeatherCards() {
            const container = document.getElementById('weatherCards');
            container.innerHTML = '';  // 清空旧数据

            if (weatherData.types.length === 0) {
                container.innerHTML = `
                    <div class="col-span-full text-center py-12">
                        <i class="fa fa-inbox text-4xl text-neutral-500 mb-4"></i>
                        <p class="text-medium">暂无天气数据</p>
                    </div>
                `;
                document.getElementById('weatherCardCount').textContent = '暂无天气类型数据';
                return;
            }

            // 排序：按天数从多到少
            const sortedWeather = weatherData.types.map((type, index) => ({
                type,
                count: weatherData.counts[index]
            })).sort((a, b) => b.count - a.count);

            sortedWeather.forEach(({ type, count }, index) => {
                const config = WEATHER_CONFIG[type] || WEATHER_CONFIG._default;
                const percentage = ((count / weatherData.total_days) * 100).toFixed(1);

                const card = document.createElement('div');
                card.className = `border rounded-xl p-5 card-animate ${config.class} neon-border`;
                card.innerHTML = `
                    <div class="flex justify-between items-start mb-4">
                        <div class="w-12 h-12 rounded-full ${config.gradient} flex items-center justify-center">
                            <i class="fa ${config.icon} text-xl" style="color:${config.color}"></i>
                        </div>
                        <span class="text-xs font-medium bg-neutral-700/80 text-light px-2 py-1 rounded-full">
                            第${index + 1}位
                        </span>
                    </div>
                    <h3 class="text-lg font-bold text-light mb-2">${type}</h3>
                    <div class="flex justify-between items-center mb-3">
                        <span class="text-sm text-medium">出现天数</span>
                        <span class="text-lg font-bold text-light">${count} 天</span>
                    </div>
                    <div class="w-full bg-neutral-700 rounded-full h-2 mb-1">
                        <div class="bg-primary h-2 rounded-full" style="width: ${percentage}%"></div>
                    </div>
                    <div class="flex justify-between text-xs text-medium">
                        <span>0%</span>
                        <span>${percentage}%</span>
                        <span>100%</span>
                    </div>
                `;

                container.appendChild(card);
            });

            // 更新卡片计数
            document.getElementById('weatherCardCount').textContent = `共 ${weatherData.types.length} 种天气类型`;
        }

        // 显示错误消息
        function showError(message) {
            const errorEl = document.getElementById('chartError');
            document.getElementById('errorMessage').textContent = message;
            errorEl.classList.remove('translate-y-[-100px]', 'opacity-0');
            errorEl.classList.add('translate-y-0', 'opacity-100');

            setTimeout(() => {
                errorEl.classList.remove('translate-y-0', 'opacity-100');
                errorEl.classList.add('translate-y-[-100px]', 'opacity-0');
            }, 5000);
        }

        // 更新数据概览
        function updateSummaryCards() {
            document.getElementById('currentCity').textContent = weatherData.urban;
            document.getElementById('totalDays').textContent = `${weatherData.total_days} 天`;
            document.getElementById('weatherTypesCount').textContent = `${weatherData.types.length} 种`;
            document.getElementById('currentDate').textContent = new Date().toLocaleDateString('zh-CN', {
                year: 'numeric',
                month: 'long',
                day: 'numeric',
                weekday: 'long'
            });

            // 更新日期范围和更新时间
            document.getElementById('dateRange').textContent = `数据覆盖期: ${weatherData.start_date} 至 ${weatherData.end_date}`;
            document.getElementById('updateTime').textContent = `数据更新时间: ${weatherData.update_time}`;
        }

        // 封装数据获取逻辑
        function fetchWeatherData(urban) {
            if (!urban) {
                showError('请选择城市');
                return;
            }

            document.getElementById('chartLoading').style.display = 'flex';

            fetch(`/menu/city_weather_stats?urban=${encodeURIComponent(urban)}`)
                .then(response => {
                    if (!response.ok) throw new Error(`获取数据失败，状态码: ${response.status}`);
                    return response.json();
                })
                .then(data => {
                    if (data.error) {
                        throw new Error(data.error);
                    }

                    // 更新全局数据
                    weatherData.urban = urban;
                    weatherData.types = data.weather_types;
                    weatherData.counts = data.counts;
                    weatherData.total_days = data.total_days;
                    weatherData.start_date = data.start_date;
                    weatherData.end_date = data.end_date;
                    weatherData.update_time = data.update_time;

                    // 重新渲染页面
                    updateSummaryCards();
                    if (weatherChart) weatherChart.dispose();
                    initChart();
                    renderWeatherCards();
                })
                .catch(error => {
                    showError(error.message || '获取数据失败，请稍后重试');
                    console.error('Fetch error:', error);
                })
                .finally(() => {
                    document.getElementById('chartLoading').style.display = 'none';
                });
        }

        // 主初始化函数
        document.addEventListener('DOMContentLoaded', () => {
            try {
                // 初始化日期显示
                document.getElementById('currentDate').textContent = new Date().toLocaleDateString('zh-CN', {
                    year: 'numeric',
                    month: 'long',
                    day: 'numeric',
                    weekday: 'long'
                });

                // 首次加载使用服务端数据
                if (weatherData.types.length > 0 && weatherData.total_days > 0) {
                    updateSummaryCards();
                    initChart();
                    renderWeatherCards();
                    document.getElementById('chartLoading').style.display = 'none';
                } else {
                    // 无服务端数据时，提示选择城市
                    document.getElementById('currentCity').textContent = "请选择城市";
                    document.getElementById('chartLoading').style.display = 'none';
                }

                // 搜索按钮点击事件
                document.getElementById('searchButton').addEventListener('click', () => {
                    const urban = document.getElementById('urban').value;
                    fetchWeatherData(urban);
                });

                // 城市选择变化事件
                document.getElementById('urban').addEventListener('change', () => {
                    const urban = document.getElementById('urban').value;
                    fetchWeatherData(urban);
                });

                // 滚动效果
                window.addEventListener('scroll', () => {
                    const header = document.getElementById('mainHeader');
                    if (window.scrollY > 20) {
                        header.classList.add('shadow-md', 'py-2');
                        header.classList.remove('shadow-sm', 'py-4');
                    } else {
                        header.classList.add('shadow-sm', 'py-4');
                        header.classList.remove('shadow-md', 'py-2');
                    }
                });

            } catch (error) {
                showError('系统初始化失败');
                console.error('Initialization error:', error);
                document.getElementById('chartLoading').style.display = 'none';
            }
        });
    </script>
</body>
</html>